/*
 *   mt_app_editor_tiny_mce.js
 *
 *   Copyright (c) 2008 ToI-Planning <office@toi-planning.net>
 * 
 *   Redistribution and use in source and binary forms, with or without
 *   modification, are permitted provided that the following conditions
 *   are met:
 * 
 *   1. Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *   2. Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 *
 *   3. Neither the name of the authors nor the names of its contributors
 *      may be used to endorse or promote products derived from this
 *      software without specific prior written permission.
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 *   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 *   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *  $Id$
 */
MT.App.Editor.Iframe = new Class( Editor.Iframe, {

    version: '0.1',
    changed: false,

    initObject: function(element, mode) {
        arguments.callee.applySuper( this, arguments );

		this.textarea_initialized = false;

		var editor = this;
		tinyMCE.init({
			elements : 'editor-content-textarea',
			init_instance_callback : function(func, ed) {
				func(ed);
				editor.tiny_mce = ed;

				var events = [
					//'onSetContent',
					//'onLoadContent',
					//'onPostProcess',
					//'onNodeChange',
					'onReset', 'onPaste',
					'onChange', 'onUndo', 'onRedo'
				];
				for (var i = 0; i < events.length; i++) {
					(function (i) {
						ed[events[i]].add(function(a) {
							editor.setChanged();
						});
					})(i);
					
				}
				document.getElementById('entry-body-field').className += ' has_tiny_mce';
			},
			setup : function(func, ed) {
				func(ed);
			},
			placemnet : null
		});
    },

	tinyMCEInitialized: function(func) {
		if (this.tiny_mce) {
			func.apply(this, []);
		}
		else {
			var editor = this;
			var id = setInterval(function() {
				if (editor.tiny_mce) {
					clearInterval(id);
					func.apply(editor, []);
				}
			}, 100);
		}
	},

	tinyMCEShow: function() {
		this.tinyMCEInitialized(function() {
			this.tiny_mce.show();
		});
	},

	tinyMCEHide: function() {
		this.tinyMCEInitialized(function() {
			this.tiny_mce.hide();
		});
	},

    /* Clear the dirty flag on the editor ( dirty == modified ) */
    clearDirty: function() {
		this.tinyMCEInitialized(function() {
			this.tiny_mce.isNotDirty = 1;
		});
    },

    /* Called to set the dirty bit on the editor and call */
    setChanged: function() {
		if (
			window.app
			&& window.app.eventSubmitForm
			&& window.app.eventSubmitForm.submitted
		) {
			return;
		}

		this.tinyMCEInitialized(function() {
			this.tiny_mce.isNotDirty = 0;
		});
		this.changed = true;

		if (window.app) {
			this.parent.setChanged();
		}
    },

    /* Focus the editor, forcing the cursor into the textarea or iframe */
    focus: function() {
		this.tinyMCEInitialized(function() {
			this.tiny_mce.focus();
		});
    },

    /* Get the editor content as html/xhtml */
    getHTML: function() {
        return this.tiny_mce.getContent();
    },

    /* Get the editor content as xhtml ( if possible, else return html ) */
    getXHTML: function() {
        return this.tiny_mce.getContent();
    },

    /* Set the html content of the editor */
    setHTML: function(value) {
		this.tinyMCEInitialized(function() {
			if (! this.textarea_initialized) {
				document.getElementById(this.tiny_mce.id).value = value;
				this.textarea_initialized = true;
			}
			this.tiny_mce.setContent(value, {format : 'raw'});
		});
    },

    /* Insert html into the editor, the editor should insert it at the cursor */
    insertHTML: function(value) {
		this.tinyMCEInitialized(function() {
			this.tiny_mce.focus();
			this.tiny_mce.selection.moveToBookmark(
				this.tiny_mce.movabletype_plugin_bookmark
			);
			this.tiny_mce.execCommand('mceInsertContent', false, value);
		});
    },

    /* Check the dirty status */
    isDirty: function() {
        return this.tiny_mce.isDirty();
    },

	placement: null
} );


App.singletonConstructor =
MT.App = new Class( MT.App, {
    initEditor: function() {
        arguments.callee.applySuper( this, arguments );

        if ( this.constructor.Editor && DOM.getElement( "editor-content" ) ) {
            var mode = DOM.getElement( "convert_breaks" );
			this.tinyMCEUpdateTextareaMode(mode.value);
        }
    },

    /* Called to fix the html in the editor before a save, or an insert.
     * inserted will be defined if called to fix inserted text
     */
    fixHTML: function( inserted ) { },

	tinyMCEUpdateTextareaMode: function(mode) {
		var formated = getByID('formatted');
		var resizer = (function() {
			var divs = formated.getElementsByTagName('div');
			for (var i = 0; i < divs.length; i++) {
				if (divs[i].className.match(/resizer/)) {
					return divs[i];
				}
			}
			return null;
		})();
		var enclosure = getByID('editor-content-enclosure');

		if (mode == 'richtext') {
			getByID('editor-content-toolbar').style.display = 'none';
			getByID('editor-content-iframe').style.display = 'none';
			resizer.style.display = 'none';

			enclosure.save_border_width = enclosure.style.borderWidth;
			enclosure.save_height = enclosure.style.height;

			enclosure.style.borderWidth = '0px';
			enclosure.style.height = 'auto';

			if (this.editor.iframe) {
				this.editor.iframe.tinyMCEShow();
			}
		}
		else {
			getByID('editor-content-toolbar').style.display = '';
			getByID('editor-content-iframe').style.display = '';
			resizer.style.display = '';

			enclosure.style.borderWidth = enclosure.save_border_width || '';
			enclosure.style.height = enclosure.save_height || '250px';

			if (this.editor.iframe) {
				this.editor.iframe.tinyMCEHide();
			}
        }
	},

    /* Called to set the editor to non rich text mode */
    setTextareaMode: function( event ) {
		this.tinyMCEUpdateTextareaMode(event.target.value);
        arguments.callee.applySuper( this, arguments );
    },

    /* This clears the editor's dirty flag */
    clearDirty: function() {
		if (this.editor.iframe) {
			this.editor.iframe.clearDirty();
		}
        return arguments.callee.applySuper( this, arguments );
    },

	placement: null
} );
